import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/tool/Toast.dart';
import 'package:flutter_yres/tool/BlankToolBarTool.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class PayPwdPage extends StatefulWidget {
  PayPwdPage({Key key}) : super(key: key);

  @override
  _PayPwdPageState createState() => _PayPwdPageState();
}

class _PayPwdPageState extends State<PayPwdPage> {
  final _userCodeController = TextEditingController(); //验证码
  final _userPwdController = TextEditingController(); //密码
  final _userPwdController2 = TextEditingController(); //密码
  // 响应空白处的焦点的Node
  BlankToolBarModel barModel = BlankToolBarModel();
  ScrollController scrollController = ScrollController();

  Timer _countdownTimer;
  int _countdownNum = 59;
  String codeString = "获取验证码";
  int codeStatus = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('设置支付密码'),
        ),
        body: BlankToolBarTool.blankToolBarWidget(context,
            model: barModel,
            body: Container(
                margin: EdgeInsets.fromLTRB(0, kWindowstateHeight, 0, 0),
                height: ScreenUtil.getInstance().setHeight(1334) - kWindowstateHeight - 56,
                child: SingleChildScrollView(
                    controller: scrollController,
                    child: Column(
                      children: <Widget>[
                        Container(
                            child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                              createBtnInputText(_userCodeController,
                                  hint: '请输入验证码',
                                  title: '手机验证码',
                                  obscureText: false,
                                  type: TextInputType.phone),
                              createInputText(_userPwdController,
                                  hint: '请输入密码',
                                  text: '新密码',
                                  obscureText: true,
                                  type: TextInputType.visiblePassword),
                              createInputText(_userPwdController2,
                                  hint: '请再次输入密码',
                                  text: '确认新密码',
                                  obscureText: true,
                                  type: TextInputType.visiblePassword),
                              new Container(
                                  margin: EdgeInsets.fromLTRB(
                                      0.0, ScreenUtil.getInstance().setWidth(20) * 2, 0, 0.0),
                                  width: ScreenUtil.getInstance().setWidth(750) * 0.8,
                                  child: new RaisedButton(
                                      color: Colors.blue,
                                      shape: StadiumBorder(),
                                      child: new Padding(
                                        padding: new EdgeInsets.all(10.0),
                                        child: new Text(
                                          '保存',
                                          style: new TextStyle(
                                              color: Colors.white,
                                              fontSize: 16.0),
                                        ),
                                      ),
                                      onPressed: () {
                                        _getLoginMsg();
                                      })),
                            ])),
                      ],
                    )))));
  }

  //文字 + 输���框
  Widget createInputText(TextEditingController controller,
      {obscureText: false, String hint, String text, TextInputType type}) {
    FocusNode focusNode = barModel.getFocusNodeByController(controller);
    return Padding(
        padding:
            new EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20) * 2, ScreenUtil.getInstance().setWidth(20), ScreenUtil.getInstance().setWidth(20) * 2, 0),
        child: new Stack(
          alignment: new Alignment(1.0, 1.0),
          //statck
          children: <Widget>[
            new Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  new Padding(
                    padding: new EdgeInsets.fromLTRB(0.0, 0.0, 5.0, 0.0),
                    child: new Text(text),
                  ),
                  new Container(
                    width: ScreenUtil.getInstance().setWidth(750) * 0.6,
                    child: new TextField(
                        // focusNode: _contentFocusNode,
                        controller: controller,
                        keyboardType: type,
                        decoration: new InputDecoration(
                          border: InputBorder.none,
                          hintText: hint,
                        ),
                        obscureText: obscureText,
                        focusNode: focusNode),
                  ),
                  new IconButton(
                    icon: new Icon(Icons.clear, color: Colors.black45),
                    onPressed: () {
                      controller.clear();
                    },
                  ),
                ]),
            Divider(
              height: 1,
            ),
          ],
        ));
  }

  //图标 + 输入框+ 按钮
  Widget createBtnInputText(TextEditingController controller,
      {obscureText: false, String hint, String title, TextInputType type}) {
    return Padding(
        padding:
            new EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20) * 2, ScreenUtil.getInstance().setWidth(20), ScreenUtil.getInstance().setWidth(20) * 2, 0),
        child: new Stack(
          alignment: new Alignment(1.0, 1.0),
          //statck
          children: <Widget>[
            new Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  new Padding(
                    padding: new EdgeInsets.fromLTRB(0.0, 0.0, 5.0, 0.0),
                    child: Text(title),
                  ),
                  new Container(
                    width: ScreenUtil.getInstance().setWidth(750) * 0.5,
                    child: new TextField(
                        // focusNode: _contentFocusNode,
                        controller: controller,
                        keyboardType: type,
                        decoration: new InputDecoration(
                          border: InputBorder.none,
                          hintText: hint,
                        ),
                        obscureText: obscureText),
                  ),
                  new MaterialButton(
                    // color: codeStatus == 1 ? Colors.blue : Colors.grey,
                    textColor: codeStatus == 1 ? Colors.blue : Colors.grey,
                    child: new Text(
                      codeString,
                      style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(20)),
                    ),
                    onPressed: () {
                      sendCode();
                    },
                  ),
                ]),
            Divider(
              height: 1,
            ),
          ],
        ));
  }

  sendCode() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    var token = preferences.get("token");
    if (token == null || token == '') {
      //未登陆
      Navigator.of(context).pushNamed("login");
    } else {
//发送短信验证码
      Map map = Map();
      map["token"] = token;
      // map['type'] = "mkyx.sms";
      // map = getSign(map);
FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
      // FormData data = new FormData.fromMap({
      //   "token": map['token'],
      //   "timestamp": map['timestamp'],
      //   "data_type": map['data_type'],
      //   "version": map['version'],
      //   "sign": map['sign'],
      //   'type': map['type']
      // });
      Response<String> response =
          await HttpUtil().post(Api.SendDrawPwdCodeUrl, data: data);
      Map userMap = json.decode(response.data);
      Toast.toast(context, msg: userMap['msg']);
      int code = userMap['code'];
      if (code == 1) {
        print(userMap);
        setState(() {
          codeStatus = 0;
          if (_countdownTimer != null) {
            return;
          }
          codeString = '${_countdownNum--}重新获取';
          _countdownTimer =
              new Timer.periodic(new Duration(seconds: 1), (timer) {
            setState(() {
              if (_countdownNum > 0) {
                codeStatus = 0;
                codeString = '${_countdownNum--}重新获取';
              } else {
                codeString = '获取验证码';
                codeStatus = 1;
                _countdownNum = 59;
                _countdownTimer.cancel();
                _countdownTimer = null;
              }
            });
          });
        });
      }
    }
  }

  void _getLoginMsg() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    var token = preferences.get("token");
    if (token == null || token == '') {
      //未登陆
      Navigator.of(context).pushNamed("login");
    } else {
      _requestForget(token);
    }
  }

  // 保存密码
  void _saveLoginMsg() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString("pwd", _userPwdController.text);
  }

  _requestForget(token) async {
    if (_userCodeController.text == '' ||
        _userPwdController.text == '' ||
        _userPwdController2.text == '') {
      Toast.toast(context, msg: '填写完整信息');
      return;
    }
    if (_userPwdController2.text != _userPwdController.text) {
      Toast.toast(context, msg: '两次密码不一致');
      return;
    }
    // FocusScope.of(context).requestFocus();
    FormData formData = new FormData.fromMap({
      'token': token,
      "code": _userCodeController.text,
      "pwd1": _userPwdController.text,
      "pwd2": _userPwdController2.text
    });
    print(formData);
    Response<String> response =
        await HttpUtil().post(Api.SetDrawPwdUrl, data: formData);
    Map userMap = json.decode(response.data);
    print(userMap);
    Toast.toast(context, msg: userMap['msg']);
    int code = userMap['code'];
    if (code == 1) {
      _saveLoginMsg();
      // Navigator.pop(context, '');
    } else {}
  }
}
